package org.keyyond.ms.core.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

public class HttpUtil {

	private static Logger log = Logger.getLogger(HttpUtil.class);

	public static String sendGet(String url, String encodeStr) {
		String response = null;
		log.info("url: " + url);
		try {
			CloseableHttpClient httpclient = null;
			CloseableHttpResponse httpresponse = null;
			try {
				httpclient = HttpClients.createDefault();
				HttpGet httpGet = new HttpGet(url);
				httpGet.addHeader("User-Agent",
						"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
				httpGet.setURI(new java.net.URI(url));
				httpresponse = httpclient.execute(httpGet);
				HttpEntity entity = httpresponse.getEntity();
				if (null != entity) {
					response = EntityUtils.toString(httpresponse.getEntity(), encodeStr);
				}
				log.info("response: " + response);
			} finally {
				if (httpclient != null) {
					httpclient.close();
				}
				if (httpresponse != null) {
					httpresponse.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	// post请求方法
	public static String sendPost(String url, String data, String encodeStr) {
		String response = null;
		log.info("url: " + url);
		log.info("request: " + data);
		try {
			CloseableHttpClient httpclient = null;
			CloseableHttpResponse httpresponse = null;
//			HttpResponse httpresponse = null;
			try {
				httpclient = HttpClients.createDefault();
				HttpPost httppost = new HttpPost(url);
				StringEntity stringentity = new StringEntity(data,
						ContentType.create("application/x-www-form-urlencoded", encodeStr));
				httppost.setEntity(stringentity);
				httpresponse = httpclient.execute(httppost);
				response = EntityUtils.toString(httpresponse.getEntity());
				log.info("response: " + response);
			} finally {
				if (httpclient != null) {
					httpclient.close();
				}
				if (httpresponse != null) {
					httpresponse.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	public static String doPostMultipartFile(String url, MultipartFile file, String type) throws Exception {
        //上传素材
        String path=url+"&type="+type;
//		String path = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=8_96qiyvdDtj88jg2xogee4NrFmbLwf_a0uI5Tcd5MCgiWT5lc7XRahcDTBVatIQoqZ9gcV7I_ulP8Nc2Vv9BO-LPpLQLctzFAG46XfS7XcZziucEurr53VDSvN1pi8XL34_ONbnge64mtViTeHLWeADAUYJ&type=image";
        String result =null;
        URL realUrl = new URL(path);

        URLConnection con= realUrl.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false); // post方式不能使用缓存
        // 设置请求头信息
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        // 设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type",
                "multipart/form-data; boundary="
                + BOUNDARY);

        // 请求正文信息
        // 第一部分：
        StringBuilder sb = new StringBuilder();
        sb.append("--"); // 必须多两道线
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"media\";filelength=\""+file.getSize()+"\";filename=\""
                + file.getOriginalFilename() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        byte[] head = sb.toString().getBytes("utf-8");
        // 获得输出流
        OutputStream out = new DataOutputStream(con.getOutputStream());
        // 输出表头
        out.write(head);
        // 文件正文部分
        // 把文件已流文件的方式 推入到url中
        DataInputStream in = new DataInputStream(file.getInputStream());
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        // 结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
        out.write(foot);
        out.flush();
        out.close();
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        try {
            // 定义BufferedReader输入流来读取URL的响应
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            if (result == null) {
                result = buffer.toString();
            }
        } catch (IOException e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
            throw new IOException("数据读取异常");
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return result.toString();
	}

	public static String doPostFile(String url, File file, String encode) {
	    String response = null;
		log.info("url: " + url);
		log.info("request: " + file.getName());
		try {
			CloseableHttpClient httpclient = null;
			CloseableHttpResponse httpresponse = null;
			try {
				httpclient = HttpClients.createDefault();
				HttpPost httppost = new HttpPost(url);
				FileEntity fileEntity = new FileEntity(file);
				httppost.setEntity(fileEntity);
				httpresponse = httpclient.execute(httppost);
				response = EntityUtils.toString(httpresponse.getEntity());
				log.info("response: " + response);
			} finally {
				if (httpclient != null) {
					httpclient.close();
				}
				if (httpresponse != null) {
					httpresponse.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	public static String upLoadWxImg(String url, File file, String encode) throws Exception {

	        //上传素材
	        String path=url;
	        String result =null;
	        URL realUrl = new URL(path);

	        URLConnection con= realUrl.openConnection();
	        con.setDoInput(true);
	        con.setDoOutput(true);
	        con.setUseCaches(false); // post方式不能使用缓存
	        // 设置请求头信息
	        con.setRequestProperty("Connection", "Keep-Alive");
	        con.setRequestProperty("Charset", encode);
	        // 设置边界
	        String BOUNDARY = "----------" + System.currentTimeMillis();
	        con.setRequestProperty("Content-Type",
	                "multipart/form-data; boundary="
	                + BOUNDARY);

	        // 请求正文信息
	        // 第一部分：
	        StringBuilder sb = new StringBuilder();
	        sb.append("--"); // 必须多两道线
	        sb.append(BOUNDARY);
	        sb.append("\r\n");
	        sb.append("Content-Disposition: form-data;name=\"media\";filelength=\""+file.length()+"\";filename=\""
	                + file.getName() + "\"\r\n");
	        sb.append("Content-Type:application/octet-stream\r\n\r\n");
	        byte[] head = sb.toString().getBytes("utf-8");
	        // 获得输出流
	        OutputStream out = new DataOutputStream(con.getOutputStream());
	        // 输出表头
	        out.write(head);
	        // 文件正文部分
	        // 把文件已流文件的方式 推入到url中
	        DataInputStream in = new DataInputStream(new FileInputStream(file));
	        int bytes = 0;
	        byte[] bufferOut = new byte[1024];
	        while ((bytes = in.read(bufferOut)) != -1) {
	            out.write(bufferOut, 0, bytes);
	        }
	        in.close();
	        // 结尾部分
	        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
	        out.write(foot);
	        out.flush();
	        out.close();
	        StringBuffer buffer = new StringBuffer();
	        BufferedReader reader = null;
	        try {
	            // 定义BufferedReader输入流来读取URL的响应
	            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                buffer.append(line);
	            }
	            if (result == null) {
	                result = buffer.toString();
	            }
	        } catch (IOException e) {
	            System.out.println("发送POST请求出现异常！" + e);
	            e.printStackTrace();
	            throw new IOException("数据读取异常");
	        } finally {
	            if (reader != null) {
	                reader.close();
	            }
	        }
	        return result.toString();
	}

	public static String doPostXml(String url, String xml, String encodeStr) {
	    String response = null;
	    log.info("url: " + url);
	    log.info("request: " + xml);
	    try {
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse httpresponse = null;
		try {
			httpclient = HttpClients.createDefault();
			HttpPost httppost = new HttpPost(url);
			StringEntity stringentity = new StringEntity(xml,
					ContentType.create("application/text/xml", encodeStr));
			httppost.setEntity(stringentity);
			httpresponse = httpclient.execute(httppost);
			response = EntityUtils.toString(httpresponse.getEntity());
			log.info("response: " + response);
		} finally {
			if (httpclient != null) {
				httpclient.close();
			}
			if (httpresponse != null) {
				httpresponse.close();
			}
		}
	    }catch (Exception e) {
		e.printStackTrace();
	}
	return response;
	}
}
